using System.Text.Json;
using Cola.Core.Skill;
using Cola.Core.Skill.NativeSkills.HistoryEvent;
using Cola.Core.Skill.Utils;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.KernelExtensions;
using Microsoft.SemanticKernel.Orchestration;

namespace Cola.Core.Business.HistoryEvent;

public class HistoryEventService : IHistoryEventService {
    private IKernel _kernel;
    private ISKFunction _classify;
    private ISKFunction _extractTimeSpan;
    private ILogger<HistoryEventService> _logger;

    public HistoryEventService(ILogger<IKernel> kernelLogger,
        IKernelProvider kernelProvider, IDateTimeNativeSkill dateTimeNativeSkill,
        IHistoryEventNativeSkill historyEventNativeSkill,
        ILogger<HistoryEventService> logger) {
        _kernel = kernelProvider.GetKernel(kernelLogger);
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));

        _kernel.ImportSkill(dateTimeNativeSkill, "DateTimeNativeSkill");
        _kernel.ImportSkill(historyEventNativeSkill, "HistoryEventNativeSkill");
        var historyEventSemanticSkill =
            _kernel.ImportSemanticSkillFromDirectory(
                ProjectFile.GetSkillsFolder(), "HistoryEventSemanticSkill");
        _classify = historyEventSemanticSkill["Classify"];
        _extractTimeSpan = historyEventSemanticSkill["ExtractTimeSpan"];
    }

    public async Task<string> ClassifyAsync(string ask) {
        var context = new ContextVariables(ask);
        var result = await _kernel.RunAsync(context, _classify);
        return result.Result;
    }

    public async Task<IList<(DateOnly, DateOnly)>> ExtractTimeSpanAsync(
        string ask, string eventType) {
        var context = new ContextVariables(ask);
        context.Set("eventType", eventType);
        var result = await _kernel.RunAsync(context, _extractTimeSpan);
        return JsonSerializer.Deserialize<IList<(DateOnly, DateOnly)>>(
            result.Result, new JsonSerializerOptions { IncludeFields = true });
    }
}